package losrebellos.lospistoleros.components.media.image 
{
	import losrebellos.console.Console;
	import losrebellos.events.IMGEvent;
	import losrebellos.lospistoleros.core.controller.sprite.PControllerSprite;
	import losrebellos.lospistoleros.core.model.sprite.IPModelSprite;
	import losrebellos.lospistoleros.core.view.sprite.IPViewSprite;
	import losrebellos.lospistoleros.events.PLoadingEvent;
	import losrebellos.media.Library;

	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	/*
	 *
	 * @author los rebellos - ben@benoitvinay.com
	 *
	 */
	public class PIMGController extends PControllerSprite 
	{
		/*
		 *
		 * CONSTRUCTOR
		 *
		 */
		public function PIMGController(m:IPModelSprite, v:IPViewSprite = null, name:String = null, type:String = null)
		{
			super(m, v, name, type);
		}
		protected function get _pimgModel():PIMGModel
		{
			return _model as PIMGModel;
		}

		
		/*
		 * 
		 * LOAD
		 * 
		 */
		public function load(request:URLRequest, context:LoaderContext):void
		{
			_pimgModel.addEventListener(PLoadingEvent.PROGRESS, progressHandler);
			_pimgModel.addEventListener(PLoadingEvent.COMPLETE, completeHandler);
			_pimgModel.addEventListener(PLoadingEvent.ERROR, errorHandler);
			_pimgModel.load(request, context);
		}
		
		
		/*
		 * 
		 * HANDLERS
		 * 
		 */
		protected function progressHandler(e:PLoadingEvent):void
		{
			Console.output(this, "PIMGController:progressHandler " + e.percentLoaded);
		}
		protected function completeHandler(e:PLoadingEvent):void
		{
			_pimgModel.removeEventListener(PLoadingEvent.PROGRESS, progressHandler);
			_pimgModel.removeEventListener(PLoadingEvent.COMPLETE, completeHandler);
			_pimgModel.removeEventListener(PLoadingEvent.ERROR, errorHandler);
			
			_view.addChild(Library.instance.getItemAsBitmap(_pimgModel.url));
			
			this.dispatchEvent(new IMGEvent(IMGEvent.COMPLETE));
		}
		protected function errorHandler(e:PLoadingEvent):void
		{
			_pimgModel.removeEventListener(PLoadingEvent.PROGRESS, progressHandler);
			_pimgModel.removeEventListener(PLoadingEvent.COMPLETE, completeHandler);
			_pimgModel.removeEventListener(PLoadingEvent.ERROR, errorHandler);
			
			this.dispatchEvent(new IMGEvent(IMGEvent.ERROR));
		}
	}
}